package middlewares

import (
	"MyBlogv2/common/HttpCode"
	"MyBlogv2/common/helper"
	"MyBlogv2/common/models"
	"MyBlogv2/common/redisUtil"
	"MyBlogv2/common/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
)

// 权限控制+认证
func AuthPermission(permission string) gin.HandlerFunc {
	return func(c *gin.Context) {
		const BearerPrefix = "Bearer "
		auth := c.GetHeader("authorization")
		if !strings.HasPrefix(auth, BearerPrefix) {
			c.Abort()
			response.ResponseError(c, HttpCode.NOT_LOGIN)
			return
		}
		auth = strings.TrimPrefix(auth, BearerPrefix)
		fmt.Println("auth:", auth)
		userClaim, err := helper.AnalysisToken(auth)
		if err != nil || userClaim == nil {
			fmt.Println("校验出错")
			c.Abort()
			response.ResponseError(c, HttpCode.NOT_LOGIN)
			return

		}
		var permissions []string
		permissions, exists := redisUtil.GetUserPermission(userClaim.UserId)
		if exists == 0 {
			fmt.Println("Redis获取权限失败，从数据库中获取权限")
			models.Db.Model(new(models.UserRole)).
				Table("sys_user_role ur").
				Select("p.permission_key").
				Joins("left join sys_role_permission rp on ur.role_id = rp.role_id").
				Joins("left join sys_permission p on rp.permission_id = p.id").
				Where("ur.user_id = ?", userClaim.UserId).
				Find(&permissions)
			fmt.Println("存入Redis")
			fmt.Println("permissions:", permissions)
			redisUtil.SaveUserPermission(permissions, userClaim.UserId)
		} else {
			fmt.Println("Redis获取权限成功")
		}

		if !helper.Contains(permissions, permission) {
			fmt.Println("校验权限：", permission, "失败")
			c.Abort()
			response.ResponseError(c, HttpCode.NO_PERMISSION)
			return
		}
		fmt.Println("校验权限：", permission, "通过")

		fmt.Println("userId", userClaim.UserId)
		c.Set("userId", userClaim.UserId)
		c.Next()

	}

}
